package com.dfa.nypl.home;

import java.io.IOException;
import java.net.URLEncoder;

import org.xmlpull.v1.XmlPullParserException;

import com.dfa.nypl.common.CampaignInfo;
import com.dfa.nypl.common.EmailValidator;
import com.dfa.nypl.common.WebService;
import com.dfa.nypl.entity.MailBody;
import com.dfa.nypl.entity.ObjectUtils;
import com.dfa.nypl.entity.QuoteInfo;
import com.dfa.nypl.main.R;
import com.dfa.nypl.view.LoaderImageView;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.telephony.TelephonyManager;
import android.text.Html;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;

public class Home extends Activity {
	private Button donateButton, advocacyButton;
	private LinearLayout campaignHomeLayout, campaignDonateLayout,
			campaignAdvocacyLayout, campaignLetterLayout;
	private WebView donateWebview;
	private Spinner titleSpinner, boroughSpinner, stateSpinner, countrySpinner,
			librarySprinner;

	private static Home singletonObject;

	public static int codeBackScreen = 0;

	private Button advocacySubmit, advocacyCancel, letterSubmit, letterCancel;
	private Button donateButtonBack, advocacyButtonBack, letterButtonBack;

	private LoaderImageView campaignAtRisk;
	private LinearLayout atRiskLayout;
	private TextView campaignTitle, campaignQuote;
	private TextView quoteInfoTV;

	private CampaignInfo mCampaignInfo;
	private QuoteInfo mQuoteInfo;

	private TextView advFName, advLName, advAddr1, advAddr2, advCity,
			advZipCode, advEmail, advPhone;
	private ToggleButton receiveNewEmailButton;
	private TextView letterMailSubject, letterMailSigOf, letterName,
			letterAddress1, letterAddress2, letterCity, letterMailBody;
	private LinearLayout donateProgressbarLayout;

	private String addrOneString, addrTwoString, boroughString, cityString,
			countryCodeString, emailString, firstNameString, lastNameString,
			libraryIdString, mailBodyString, mailSigOfString,
			mailSubjectString, phoneString, postalCodeString, stateString,
			titleString;

	private boolean confirmEmailsOk;
	private int districtId = 0;

	private MailBody mMailInfo;

	private TelephonyManager telephonyManager;
	private WakeLock lock;
	private ConnectivityManager connectivityManager;

	public static Home getSingletonHome() {
		if (singletonObject == null) {
			singletonObject = new Home();
		}
		return singletonObject;
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		setContentView(R.layout.home);
		super.onCreate(savedInstanceState);

		connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);

		telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);

		initWakeLock();

		codeBackScreen = 0;

		donateButton = (Button) findViewById(R.id.donate_button);
		advocacyButton = (Button) findViewById(R.id.advocacy_button);

		atRiskLayout = (LinearLayout) findViewById(R.id.at_risk_layout);
		campaignTitle = (TextView) findViewById(R.id.campaign_title);
		campaignQuote = (TextView) findViewById(R.id.campaign_quote);

		quoteInfoTV = (TextView) findViewById(R.id.campaign_quote);

		campaignHomeLayout = (LinearLayout) findViewById(R.id.campaign_home_layout);
		campaignDonateLayout = (LinearLayout) findViewById(R.id.campaign_donate_layout);
		campaignAdvocacyLayout = (LinearLayout) findViewById(R.id.campaign_writer_layout1);
		campaignLetterLayout = (LinearLayout) findViewById(R.id.campaign_letter_layout);
		donateProgressbarLayout = (LinearLayout) findViewById(R.id.donate_progressbar_layout);

		donateWebview = (WebView) findViewById(R.id.donate_webview);
		donateWebview.getSettings().setJavaScriptEnabled(true);
		donateWebview.getSettings().setSupportZoom(true);

		titleSpinner = (Spinner) findViewById(R.id.title_spinner);
		boroughSpinner = (Spinner) findViewById(R.id.borough_spinner);
		stateSpinner = (Spinner) findViewById(R.id.state_spinner);
		countrySpinner = (Spinner) findViewById(R.id.country_spinner);
		librarySprinner = (Spinner) findViewById(R.id.library_spinner);

		advocacySubmit = (Button) findViewById(R.id.advocacy_submit);
		advocacyCancel = (Button) findViewById(R.id.advocacy_cancel);
		letterSubmit = (Button) findViewById(R.id.letter_submit);
		letterCancel = (Button) findViewById(R.id.letter_cancel);

		letterName = (TextView) findViewById(R.id.letter_name);
		letterAddress1 = (TextView) findViewById(R.id.letter_addr_1);
		letterAddress2 = (TextView) findViewById(R.id.letter_addr_2);
		letterCity = (TextView) findViewById(R.id.letter_city);
		letterMailBody = (TextView) findViewById(R.id.letter_mail_body);

		donateButtonBack = (Button) findViewById(R.id.donate_back_button);
		advocacyButtonBack = (Button) findViewById(R.id.advocacy_back_button);
		letterButtonBack = (Button) findViewById(R.id.letter_back_button);

		advFName = (TextView) findViewById(R.id.writer_first_name);
		advLName = (TextView) findViewById(R.id.writer_last_name);
		advAddr1 = (TextView) findViewById(R.id.writer_address_one);
		advAddr2 = (TextView) findViewById(R.id.writer_address_two);
		advCity = (TextView) findViewById(R.id.writer_city);
		advZipCode = (TextView) findViewById(R.id.writer_zip_code);
		advEmail = (TextView) findViewById(R.id.writer_email);
		advPhone = (TextView) findViewById(R.id.writer_phone);

		new InitData().execute();
		
		letterMailSubject = (TextView) findViewById(R.id.letter_future);
		letterMailSigOf = (TextView) findViewById(R.id.letter_sincerely);

		receiveNewEmailButton = (ToggleButton) findViewById(R.id.writer_receive_email);

		donateButtonBack.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				setHomeView();
			}
		});
		advocacyButtonBack.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				setHomeView();
			}
		});
		letterButtonBack.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				setAdvacacyButtonView();
			}
		});

		donateButton.setOnClickListener(new DonateListener());
		advocacyButton.setOnClickListener(new AdcocacyListener());

		advocacySubmit.setOnClickListener(new RedirectLetterFormListener());
		advocacyCancel.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				resetAdvocacyForm();
			}

		});
		letterCancel.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				resetLetterForm();

			}
		});

		letterSubmit.setOnClickListener(new LetterSubmitListener());

	}

	@Override
	protected void onPause() {
		super.onPause();
		lock.release();
	}

	@Override
	protected void onResume() {
		super.onResume();
		lock.acquire();

	}

	private void initWakeLock() {
		PowerManager powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
		lock = powerManager.newWakeLock(PowerManager.FULL_WAKE_LOCK
				| PowerManager.ON_AFTER_RELEASE, "LiveGPSTraking");
	}

	private boolean isConnected() {
		if (telephonyManager == null || connectivityManager == null) {
			return false;
		}

		final boolean roaming = telephonyManager.isNetworkRoaming();
		final NetworkInfo info = connectivityManager.getActiveNetworkInfo();

		return info != null && info.isConnected() && !roaming;
	}

	// when cancel button at letters form click
	private void resetLetterForm() {
		letterMailSubject.setText("");
		letterMailSigOf.setText("");
		letterMailBody.setText("");
	}

	// when cancel button click
	private void resetAdvocacyForm() {
		advFName.setText("");
		advLName.setText("");
		advAddr1.setText("");
		advAddr2.setText("");
		advCity.setText("");
		advZipCode.setText("");
		advEmail.setText("");
		advPhone.setText("");
		titleSpinner.setSelection(0);
		boroughSpinner.setSelection(0);
		stateSpinner.setSelection(0);
		countrySpinner.setSelection(0);
		librarySprinner.setSelection(0);
		receiveNewEmailButton.setSelected(true);

	}

	// donate button click
	private class DonateListener implements OnClickListener {

		public void onClick(View v) {
			setDonateButtonView();
			if (!isConnected()) {
				Toast.makeText(Home.this, "Network unable to connect",
						Toast.LENGTH_SHORT).show();
				donateProgressbarLayout.setVisibility(View.GONE);
			} else {
				donateProgressbarLayout.setVisibility(View.VISIBLE);
				donateWebview
						.loadUrl("https://secure3.convio.net/nypl/site/SPageNavigator/2011_advocacy.html&s_src=FRS11AP_QMSDN");
				donateWebview.setWebChromeClient(new WebChromeClient() {
					public void onProgressChanged(WebView view, int progress) {
						if (progress == 100)
							donateProgressbarLayout.setVisibility(View.GONE);
					}
				});
			}

		}

	}

	// writer button click
	private class AdcocacyListener implements OnClickListener {
		public void onClick(View v) {
			setAdvacacyButtonView();
			// init data
			initDataForAdvocacy();
		}
	}

	private void setDonateButtonView() {
		campaignHomeLayout.setVisibility(View.GONE);
		campaignDonateLayout.setVisibility(View.VISIBLE);
		campaignAdvocacyLayout.setVisibility(View.GONE);
		campaignLetterLayout.setVisibility(View.GONE);
		codeBackScreen = 1;
	}

	private void setAdvacacyButtonView() {
		campaignLetterLayout.setVisibility(View.GONE);
		campaignHomeLayout.setVisibility(View.GONE);
		campaignDonateLayout.setVisibility(View.GONE);
		campaignAdvocacyLayout.setVisibility(View.VISIBLE);

		codeBackScreen = 2;
	}

	private void initLetterForm() {
		// init form persion info
		String name = titleSpinner.getSelectedItem().toString();
		name += ". ";
		name += advFName.getText().toString();
		name += " " + advLName.getText().toString();

		String address1 = advAddr1.getText().toString();
		String address2 = advAddr2.getText().toString();

		String city = advCity.getText().toString() + ", ";
		city += getResources().getStringArray(R.array.state_code)[stateSpinner
				.getSelectedItemPosition()]
				+ ", ";
		city += advZipCode.getText().toString();

		letterName.setText(name);
		letterAddress1.setText(address1);
		if (address2 == null || address2.equals("")) {
			letterAddress2.setVisibility(View.GONE);
		} else {
			letterAddress2.setText(address2);
			letterAddress2.setVisibility(View.VISIBLE);
		}
		letterCity.setText(city);

	}

	private void setLetterButtonView() {
		campaignHomeLayout.setVisibility(View.GONE);
		campaignDonateLayout.setVisibility(View.GONE);
		campaignAdvocacyLayout.setVisibility(View.GONE);
		campaignLetterLayout.setVisibility(View.VISIBLE);
		codeBackScreen = 3;
	}

	public void setHomeView() {
		campaignHomeLayout.setVisibility(View.VISIBLE);
		campaignDonateLayout.setVisibility(View.GONE);
		campaignAdvocacyLayout.setVisibility(View.GONE);
		campaignLetterLayout.setVisibility(View.GONE);

		codeBackScreen = 0;

	}

	private void initDataForAdvocacy() {
		ArrayAdapter<?> adapter = null;
		// set title spinner
		adapter = ArrayAdapter.createFromResource(this, R.array.titles,
				android.R.layout.simple_spinner_item);
		adapter
				.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		titleSpinner.setAdapter(adapter);

		// set borough spinner
		adapter = ArrayAdapter.createFromResource(this, R.array.boroughs,
				android.R.layout.simple_spinner_item);
		adapter
				.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		boroughSpinner.setAdapter(adapter);

		// set state spinner
		adapter = ArrayAdapter.createFromResource(this, R.array.stateRegions,
				android.R.layout.simple_spinner_item);
		adapter
				.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		stateSpinner.setAdapter(adapter);

		// set Country spinner
		adapter = ArrayAdapter.createFromResource(this, R.array.countries,
				android.R.layout.simple_spinner_item);
		adapter
				.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		countrySpinner.setAdapter(adapter);

		// set Library spinner
		adapter = ArrayAdapter.createFromResource(this, R.array.libraries,
				android.R.layout.simple_spinner_item);
		adapter
				.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		librarySprinner.setAdapter(adapter);

		// reset adapter
		adapter = null;

	}

	private class RedirectLetterFormListener implements OnClickListener {
		private StringBuilder messageBuilder;
		EmailValidator emailValidor;

		public RedirectLetterFormListener() {
			messageBuilder = new StringBuilder();
			emailValidor = new EmailValidator();
		}

		public void onClick(View v) {
			messageBuilder.setLength(0);
			if (advFName.getText().toString() == null
					|| advFName.getText().toString().equals("")) {
				messageBuilder.append("- Please enter your First Name\n");
			}
			if (advLName.getText().toString() == null
					|| advLName.getText().toString().equals("")) {
				messageBuilder.append("- Please enter your Last Name\n");
			}
			if (advAddr1.getText().toString().toString() == null
					|| advAddr1.getText().toString().equals("")) {
				messageBuilder.append("- Please enter your Address 1\n");
			}
			if (advCity.getText().toString() == null
					|| advCity.getText().toString().equals("")) {
				messageBuilder.append("- Please enter your City\n");
			}

			if (advZipCode.getText().toString() == null
					|| advZipCode.getText().toString().equals("")) {
				messageBuilder.append("- Please enter your Postal Code\n");
			} else if (advZipCode.getText().toString().trim().length() < 5) {
				messageBuilder
						.append("- Enter Your Postal Code has length >5\n");
			}
			if (advEmail.getText().toString() == null
					|| advEmail.getText().toString().equals("")) {
				messageBuilder.append("- Please enter a valid email\n");
			} else if (!emailValidor.validate(advEmail.getText().toString()
					.trim())) {
				messageBuilder.append("- Please enter a valid email\n");
			}
			if (messageBuilder != null && messageBuilder.length() <= 0) {
				setLetterButtonView();
				// init value
				initLetterForm();

				if (!isConnected()) {
					Toast.makeText(Home.this, "Network unable to connect",
							Toast.LENGTH_SHORT).show();
				} else {
					// get mail info to init form
					new GetMailInfoTask().execute();
				}

			} else {
				showAlertVaildateMessage(messageBuilder.toString());
			}

		}
	}

	// event when submit of letter form click
	private class LetterSubmitListener implements OnClickListener {
		StringBuilder messageBuilder;

		public LetterSubmitListener() {
			messageBuilder = new StringBuilder();
		}

		public void onClick(View v) {
			messageBuilder.setLength(0);
			if (letterMailSubject.getText().toString() == null
					|| letterMailSubject.getText().toString().equals("")) {
				messageBuilder.append("- Please enter mail subject !\n");
			}
			if (letterMailSigOf.getText().toString() == null
					|| letterMailSigOf.getText().toString().equals("")) {
				messageBuilder.append("- Please enter mail Sig Off !\n");
			}
			if (letterMailBody.getText().toString() == null
					|| letterMailBody.getText().toString().equals("")) {
				messageBuilder.append("- Please enter mail body !\n");
			}

			if (messageBuilder != null && messageBuilder.length() <= 0) {

				mailSigOfString = letterMailSigOf.getText().toString();
				mailSubjectString = letterMailSubject.getText().toString();
				mailBodyString = letterMailBody.getText().toString();
				if (!isConnected()) {
					Toast.makeText(Home.this, "Network unable to connect",
							Toast.LENGTH_SHORT).show();
				} else {
					// insert data to service
					new InsertDataTask().execute();
				}

			} else {
				showAlertVaildateMessage(messageBuilder.toString());
			}

		}

	}

	private void showAlertVaildateMessage(String message) {
		AlertDialog.Builder builder = new AlertDialog.Builder(Home.this);
		builder.setMessage(message).setTitle("Please enter valid data...")
				.setPositiveButton("Ok", new DialogInterface.OnClickListener() {

					public void onClick(DialogInterface d, int which) {
						d.dismiss();
					}
				});
		builder.create().show();
	}

	private class InsertDataTask extends AsyncTask<Void, Void, Void> {
		ProgressDialog dialog;
		String response = null;

		public InsertDataTask() {
			dialog = new ProgressDialog(Home.this);
			dialog.setMessage("Inserting...");
		}

		@Override
		protected void onPostExecute(Void result) {
			super.onPostExecute(result);
			if (dialog.isShowing()) {
				dialog.dismiss();
			}
			if (response != null) {
				if (response.indexOf("faultcode") != -1) {
					Toast.makeText(Home.this, "Error when send letter !",
							Toast.LENGTH_SHORT).show();
				} else {
					// reset form
					resetLetterForm();
					// show message
					Toast.makeText(Home.this, "You send letter successfull !",
							Toast.LENGTH_SHORT).show();

				}

			} else {
				Toast.makeText(Home.this, "Error when send letter !",
						Toast.LENGTH_SHORT).show();
			}
		}

		@Override
		protected void onPreExecute() {
			dialog.show();
			super.onPreExecute();
		}

		@Override
		protected Void doInBackground(Void... params) {

			// call webservice
			response = WebService.getSingletonService()
					.createNYPLAdvocacyCollectInfo(addrOneString,
							addrTwoString, boroughString, cityString,
							String.valueOf(confirmEmailsOk), countryCodeString,
							emailString, firstNameString, lastNameString,
							libraryIdString, URLEncoder.encode(mailBodyString),
							URLEncoder.encode(mailSigOfString),
							URLEncoder.encode(mailSubjectString), phoneString,
							postalCodeString, stateString, titleString);

			System.out.println(">>" + response);
			return null;
		}

	}

	private class GetMailInfoTask extends AsyncTask<Void, Void, Void> {
		ProgressDialog dialog;

		public GetMailInfoTask() {
			dialog = new ProgressDialog(Home.this);
			dialog.setMessage("Loading...");
		}

		@Override
		protected void onPostExecute(Void result) {
			super.onPostExecute(result);
			if (dialog.isShowing()) {
				dialog.dismiss();
			}
			// init form mail
			if (mMailInfo != null) {
				letterMailSubject.setText(mMailInfo.getMailSubject());
				letterMailBody.setText(Html.fromHtml(mMailInfo.getMailBody()));
				letterMailSigOf.setText("Sincerely");
			}

			// get value from text field
			titleString = titleSpinner.getSelectedItem().toString();
			firstNameString = advFName.getText().toString();
			lastNameString = advLName.getText().toString();
			addrOneString = advAddr1.getText().toString();
			addrTwoString = advAddr2.getText().toString();
			boroughString = getResources().getStringArray(R.array.borough_code)[boroughSpinner
					.getSelectedItemPosition()];
			cityString = advCity.getText().toString();
			stateString = getResources().getStringArray(R.array.state_code)[stateSpinner
					.getSelectedItemPosition()];
			postalCodeString = advZipCode.getText().toString();
			countryCodeString = getResources().getStringArray(
					R.array.country_code)[countrySpinner
					.getSelectedItemPosition()];
			emailString = advEmail.getText().toString();
			confirmEmailsOk = receiveNewEmailButton.isChecked();
			phoneString = advPhone.getText().toString();
			libraryIdString = getResources().getStringArray(
					R.array.library_code)[librarySprinner
					.getSelectedItemPosition()];
			// reset form
			resetAdvocacyForm();
		}

		@Override
		protected void onPreExecute() {
			dialog.show();
			super.onPreExecute();
		}

		@Override
		protected Void doInBackground(Void... params) {
			try {
				mMailInfo = WebService.getSingletonService().getMailInfo();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (XmlPullParserException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return null;
		}
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			switch (codeBackScreen) {
			case 0:
				finish();
				break;
			case 1:
				setHomeView();
				break;
			case 2:
				setHomeView();
				break;
			case 3:
				setAdvacacyButtonView();
				break;

			default:
				finish();
				break;
			}
		}
		return true;
	}

	private class InitData extends AsyncTask<Void, Void, Void> {
		ProgressDialog dialog = null;

		public InitData() {
			dialog = new ProgressDialog(Home.this);
			dialog.setMessage("Waiting...");
		}

		@Override
		protected void onPostExecute(Void result) {
			super.onPostExecute(result);
			if (dialog.isShowing()) {
				dialog.dismiss();
			}

			mCampaignInfo = ObjectUtils.campaignInfo;
			if (mCampaignInfo != null) {
				// init icon
				String photoUrl = getResources().getString(
						R.string.amazonaw_url);
				String tmp = mCampaignInfo.getCampaignImageId().substring(0, 3);
				photoUrl += tmp + "/";
				photoUrl += mCampaignInfo.getCampaignImageId();
				System.out.println("URL=" + photoUrl);
				if (isConnected()) {
					final LoaderImageView image = new LoaderImageView(Home.this,
							photoUrl);
					image.setLayoutParams(new LayoutParams(
							LayoutParams.WRAP_CONTENT,
							LayoutParams.WRAP_CONTENT));
					atRiskLayout.addView(image);
				}

				// init title
				campaignTitle.setText(Html.fromHtml(mCampaignInfo
						.getCampaignTitle()));
			}

			mQuoteInfo = ObjectUtils.quoteInfo;
			if (mQuoteInfo != null) {
				String content = mQuoteInfo.getUserQuote();
				String endLine = mQuoteInfo.getFirstName();
				endLine += "  ";
				endLine += mQuoteInfo.getLastName();
				if (content.endsWith("<br />") || content.endsWith("<br/>")) {
				} else {
					content += "<br />";
				}
				content += endLine;

				quoteInfoTV.setText(Html.fromHtml(content));
			}

		}

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			dialog.show();
		}

		@Override
		protected Void doInBackground(Void... params) {
			if (!isConnected()) {
			} else {
				try {
					ObjectUtils.campaignInfo = WebService.getSingletonService()
							.getCampaignInfo();
					ObjectUtils.quoteInfo = WebService.getSingletonService()
							.getRandomQuote();
				} catch (Exception e) {
					e.printStackTrace();
				}

			}
			return null;
		}

	}

}
